<template>
  <div>
    <a-modal
      :title="modalTitle"
      :visible="visible"
      :confirm-loading="confirmLoading"
      width="50%"
      wrapClassName="commonModalRoot"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <div id="components-form-demo-advanced-search">
        <a-form class="ant-advanced-search-form" :form="form">
          <a-row :gutter="24">
            <a-col
              v-for="(item,index) in searchArr"
              :key="index"
              :span="8">
              <a-form-item :label="item.label">
                <a-select
                  show-search
                  :value="item.value"
                  v-if="item.type == 'select'"
                  @change="getSelectData()"
                  v-decorator="[[item.key], {}]"
                >
                  <a-select-option v-for="d in item.data" :key="d.value">
                    {{ d.label }}
                  </a-select-option>
                </a-select>
                <a-date-picker v-else-if="item.type == 'dateTime'" show-time placeholder="请输入" v-decorator="[[item.key], {}]" />
                <a-input v-decorator="[[item.key], {}]" v-else  placeholder="请输入"/>
              </a-form-item>
            </a-col>
            <a-button type="primary" html-type="submit" @click="getTableData()" style="margin-top: 4px;margin-left: 10px;">
              查询
            </a-button>
          </a-row>
<!--          <a-row>-->
<!--            <a-col :span="24" :style="{ textAlign: 'right' }">-->
<!--              <a-button type="primary" html-type="submit" @click="getTableData()">-->
<!--                查询-->
<!--              </a-button>-->
<!--            </a-col>-->
<!--          </a-row>-->
        </a-form>
      </div>
      <a-table
        v-if="showATable"
        @change="handleTableChange"
        ref="dataTable"
        :row-selection="rowSelection"
        :rowSelection="{type:selectType,onChange:changeSelect}"
        :pagination="pagination"
        :columns="columns"
        :rowKey="rowKey"
        :data-source="data"
        :customRow="rowClick"
      >
        <span slot="action" slot-scope="record, index">
          <a-input v-model="record.key"></a-input>
        </span>
      </a-table>
    </a-modal>
  </div>
</template>
<script>
import { getAction } from '@/api/manage'
export default {
    data () {
        return {
            selectedRowKeys:[],
            selectedAll:[],
            pagination: {
              total: 0,
              current:1,
              pageSize: 20,//每页中显示10条数据
              showSizeChanger: true,
              pageSizeOptions: ["10", "20", "50", "100"],//每页中显示的数据
              showTotal: total => `共有 ${total} 条数据`,  //分页中显示总的数据
            },
            rowClick: record => ({
              // 事件
              on: {
                click: () => {
                  // 点击改行时要做的事情
                  // ......
                  console.log(record, 'record')
                  let rowIndex = 0;
                  this.data.forEach((e,index)=>{
                    if(record[this.rowKey] == e[this.rowKey] || (record[this.rowKey] && record[this.rowKey] == e[this.rowKey])){
                      rowIndex = index
                    }
                  })
                  let commonModal
                  let commonModalArr = document.getElementsByClassName("commonModalRoot");
                  for(let i=0;i<commonModalArr.length;i++){
                    if(commonModalArr[i].style.display !== 'none'){
                      commonModal = commonModalArr[i]
                    }
                  }
                  let inputObj
                  if(this.selectType == 'radio'){
                    inputObj = commonModal.getElementsByClassName("ant-radio-wrapper")[rowIndex];
                  }else{
                   
                    inputObj = commonModal.getElementsByClassName("ant-checkbox-wrapper")[rowIndex+1];
                  }
                  inputObj.click();
                }
              }
            }),
            showATable: true,
            form: this.$form.createForm(this, { name: 'advanced_search' }),
            selectObj: '',
            searchObj: {},
            ModalText: 'Content of the modal',
            visible: false,
            confirmLoading: false,
            data: []
        }
    },
    watch: {
        // visible (newName, oldName) {
        //   console.log('vvvvvvvvvvvvvvvvvvvvv',newName)
        //     if (newName) {
        //         if (!this.selectType) {
        //             this.selectType = 'radio'
        //         }
        //         this.searchObj = {};
        //         this.searchArr.forEach((e) => {
        //             this.searchObj[e.key] = '';
        //             if (e.value) {
        //                 this.searchObj[e.key] = e.value
        //             }
        //         })
        //         this.showATable = false
        //         this.$nextTick(() => {
        //             this.showATable = true
        //         })
        //         console.log('ggg', this.searchObj)
        //         this.getTableData()
        //
        //     }
        // }
    },
    computed: {
        rowSelection () {
            return {
                selectedRowKeys: this.historyData,
                onChange: (selectedRowKeys, selectedRows) => {
                    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
                },
                getCheckboxProps: record => ({
                    props: {
                        disabled: record.name === 'Disabled User', // Column configuration not to be checked
                        name: record.name,
                        defaultChecked:this.historyData.includes(record.id)
                    }
                })
            }
        }
    },
    props: {
        rowKey: {
          type: String,
          default: 'CompanyId'
        },
        selectType: {
            type: String,
            default: 'radio'
        },
        modalTitle: String,
        apiUrl: String,
        searchArr: Array,
        columns: Array,
        historyData:Array,
        conditions:Array,
    },
    mounted () {
        console.log('gggg', this.searchArr)
    },
    methods: {
        // rowClick(record){
        //   this.handleTableChange(record)
        // },
        getSelectData () {
            this.$forceUpdate()
        },
        changeSelect (indexArr, val) {
            this.selectObj = val
            if(this.selectType == 'checkbox'){
              val.forEach((e)=>{
                if(!this.selectedAll.some((item)=>{return item.CompanyId === e.CompanyId})){
                  this.selectedAll.push(e)
                }
              })
              this.selectedAll = this.selectedAll.filter((e)=>{
                if(indexArr.some((item)=>{return item === e.CompanyId})){
                  return e
                }
              })
              this.selectObj = this.selectedAll
            }
        },
      handleTableChange (pagination) {
        this.pagination.current = pagination.current;
        this.pagination.pageSize = pagination.pageSize;
        this.getTableData();
      },
        getTableData () {
          let searchObj = this.form.getFieldsValue();
            let params = Object.assign({
                PageIndex: this.pagination.current,
                pageSize: this.pagination.pageSize
            })
            let that = this;
            if (this.conditions) {
              params.conditions = this.conditions
            }
            if(Object.keys(searchObj).length > 0){
              let conditionObj = {
                'or':[]
              }
              // params.conditions = {
              //   'or':[]
              // }
              for(let key in searchObj){
                if(searchObj[key]){
                  conditionObj.or.push({
                    field: key,
                    operator: "like",
                    value: searchObj[key],
                  })
                }
              }
              if(conditionObj.or.length == 0){
                delete params['conditions']
              }
              params.conditions = conditionObj
            }
            params.orders = [{field: "Ts", desc: true}];
            
            this.$http.postAction(this.apiUrl, params).then((res) => {
                if (res.status == 1) {
                  if(res.data.rows){
                    this.data = res.data.rows;
                    this.pagination.total = res.data.totalCount;
                  }
                } else {
                    that.$message.warning(res.message)
                }
                this.$nextTick(()=>{
                  if(this.historyData && 0 < this.historyData.length){
                    let rowIndex = [];
                    this.data.forEach((e,index)=>{
                      if(this.historyData.some((item)=>{ return item == e.id})){
                        rowIndex.push(index)
                      }
                    })
                    let commonModal = document.getElementsByClassName("commonModalRoot")[0];
                    let inputObj
                    if(this.selectType == 'radio'){
                      inputObj = commonModal.getElementsByClassName("ant-radio-wrapper")[rowIndex[0]];
                      inputObj.click();
                    }else{
                      rowIndex.forEach((e)=>{
                        inputObj = commonModal.getElementsByClassName("ant-checkbox-wrapper")[e+1];
                        inputObj.click();
                      })
                    }
                  }
                })
                
            }).finally(() => {
                // that.close();
            })
        },
        open () {
          this.form.resetFields();
            // this.searchObj = {}
            // this.getTableData()
            this.selectObj = ''
            this.visible = true
          if (!this.selectType) {
            this.selectType = 'radio'
          }
          this.searchObj = {};
          this.searchArr.forEach((e) => {
            this.searchObj[e.key] = '';
            if (e.value) {
              this.searchObj[e.key] = e.value
            }
          })
          this.showATable = false
          this.$nextTick(() => {
            this.showATable = true
          })
          console.log('ggg', this.searchObj)
          this.getTableData()
        },
        handleOk (e) {
            if (!this.selectObj) {
                this.selectObj = []
            }
            if (this.selectObj.length == 0) {
                this.$message.error('请选择数据')
                return false
            }
            this.$emit('getCommonModalData', this.selectObj)
            this.visible = false
            this.confirmLoading = false
        },
        handleCancel (e) {
            this.close()
        },
        close () {
            this.$emit('close')
            this.visible = false
        }
    }
}
</script>
<style>
    .ant-advanced-search-form {
        padding: 12px;
        background: #fbfbfb;
        border: 1px solid #d9d9d9;
        border-radius: 6px;
    }

    .ant-advanced-search-form .ant-form-item {
        display: flex;
    }

    .ant-advanced-search-form .ant-form-item-control-wrapper {
        flex: 1;
    }

    #components-form-demo-advanced-search .ant-form {
        max-width: none;
    }
    #components-form-demo-advanced-search .search-result-list {
        margin-top: 16px;
        border: 1px dashed #e9e9e9;
        border-radius: 6px;
        background-color: #fafafa;
        min-height: 200px;
        text-align: center;
        padding-top: 80px;
    }
    .commonModalRoot .ant-modal-body{
      max-height:70vh;
      overflow: auto;
    }
    .commonModalRoot .ant-table-tbody .ant-table-row td{
      padding-top: 10px;
      padding-bottom: 10px;
    }
</style>
